package com.xusiyan08.entity;

import jakarta.persistence.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
// import java.util.List; // No longer needed directly for item images

@Converter(autoApply = true)
class ItemCategoryConverter implements AttributeConverter<Item.Category, String> {

    @Override
    public String convertToDatabaseColumn(Item.Category category) {
        if (category == null) {
            return null;
        }
        return category.getValue();
    }

    @Override
    public Item.Category convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        return Item.Category.fromValue(dbData);
    }
}

@Entity
@Table(name = "items")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long itemId;

    @Column(nullable = false, length = 100)
    private String title;

    @Column(columnDefinition = "TEXT", nullable = false)
    private String description;

    @Column(nullable = false, precision = 10, scale = 2)
    private BigDecimal price;

    @Column(nullable = false, length = 20)
    @Convert(converter = ItemCategoryConverter.class)
    private Category category;

    @Column(name = "seller_id", nullable = false)
    private Long sellerId;

    @Enumerated(EnumType.STRING)
    private Status status = Status.审核中;

    @Column(name = "view_count")
    private Integer viewCount = 0;

    @Column(name = "like_count")
    private Integer likeCount = 0;

    @Column(name = "created_at")
    private LocalDateTime createdAt = LocalDateTime.now();

    @Column(name = "updated_at")
    private LocalDateTime updatedAt = LocalDateTime.now();

    @Lob // Annotation for large objects like BLOB
    @Column(name = "images", columnDefinition = "LONGBLOB") // Explicitly define column as LONGBLOB
    private byte[] images;

    @Column(name = "primary_image_index")
    private Integer primaryImageIndex;

    @Column(name = "student_id", length = 50) // Assuming a reasonable length for studentId
    private String studentId;

    @Transient // Mark as not mapped to database column
    private String base64Image;

    @Transient // Seller's nickname for frontend display
    private String sellerNickname;

    @Transient // Flag to indicate if this is a fallback/degraded response
    private boolean isDegraded = false;

    public boolean isDegraded() {
        return isDegraded;
    }

    public void setDegraded(boolean degraded) {
        isDegraded = degraded;
    }

    public enum Category {
        BOOKS("书籍"),
        ELECTRONICS("电子产品"),
        CLOTHING("服饰鞋帽"),
        DAILY_SUPPLIES("生活用品"),
        OTHER("其他");

        private final String value;

        Category(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public static Category fromValue(String text) {
            // Handle legacy values for backward compatibility
            if ("电子".equalsIgnoreCase(text)) {
                return ELECTRONICS;
            }
            if ("服饰".equalsIgnoreCase(text)) {
                return CLOTHING;
            }

            // Match current values
            for (Category b : Category.values()) {
                if (b.getValue().equalsIgnoreCase(text)) {
                    return b;
                }
            }

            // Match by enum name as a fallback for robustness
            try {
                return Category.valueOf(text.toUpperCase());
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("Unexpected value for Category: '" + text + "'");
            }
        }
    }

    public enum Status {
        审核中, 出售中, 已售出, 已下架
    }

    // Getters and Setters
    public Long getItemId() { return itemId; }
    public void setItemId(Long itemId) { this.itemId = itemId; }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    public BigDecimal getPrice() { return price; }
    public void setPrice(BigDecimal price) { this.price = price; }

    public Category getCategory() { return category; }
    public void setCategory(Category category) { this.category = category; }

    public Long getSellerId() { return sellerId; }
    public void setSellerId(Long sellerId) { this.sellerId = sellerId; }

    public Status getStatus() { return status; }
    public void setStatus(Status status) { this.status = status; }

    public Integer getViewCount() { return viewCount; }
    public void setViewCount(Integer viewCount) { this.viewCount = viewCount; }

    public Integer getLikeCount() { return likeCount; }
    public void setLikeCount(Integer likeCount) { this.likeCount = likeCount; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }

    public LocalDateTime getUpdatedAt() { return updatedAt; }
    public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }

    // Getters and Setters for new image fields and studentId
    public byte[] getImages() { return images; }
    public void setImages(byte[] images) { this.images = images; }

    public Integer getPrimaryImageIndex() { return primaryImageIndex; }
    public void setPrimaryImageIndex(Integer primaryImageIndex) { this.primaryImageIndex = primaryImageIndex; }

    // Getter and Setter for the transient field
    public String getBase64Image() {
        return base64Image;
    }

    public void setBase64Image(String base64Image) {
        this.base64Image = base64Image;
    }

    public String getStudentId() { return studentId; }
    public void setStudentId(String studentId) { this.studentId = studentId; }

    // Getters and Setters for sellerNickname
    public String getSellerNickname() {
        return sellerNickname;
    }

    public void setSellerNickname(String sellerNickname) {
        this.sellerNickname = sellerNickname;
    }
}